package com.foreverwin.mes.meapi.controller;

import com.foreverwin.mes.core.base.FrontPage;
import com.foreverwin.mes.core.base.AjaxResult;
import com.foreverwin.mes.core.utils.CommonMethods;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.foreverwin.mes.core.utils.StringUtils;
import com.foreverwin.mes.meapi.enums.CustomFieldsConstant;
import com.foreverwin.mes.meapi.model.CustomFields;
import com.foreverwin.mes.meapi.service.CustomFieldsService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.foreverwin.mes.meapi.service.ResrceService;
import com.foreverwin.mes.meapi.model.Resrce;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 *
 * @author Syngna
 * @since 2020-01-13
 */
@Controller
@RequestMapping("/resrces")
public class ResrceController {
    private final Logger logger = LoggerFactory.getLogger(ResrceController.class);

    @Autowired
    public ResrceService resrceService;

    @Autowired
    public CustomFieldsService customFieldsService;

    /**
    * 根据id查询
    *
    * @param id 主键
    * @return
    */
    @ResponseBody
    @GetMapping("/{id:.+}")
    public AjaxResult getResrceById(@PathVariable String id) {
        Resrce result;
        try {
            result = resrceService.selectById(id);
        } catch (Exception e) {
            logger.error("getResrceById -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success(result);
    }

    /**
     * 根据资源名称查询
     *
     * @param resrce 资源名称
     * @return
     */
    @ResponseBody
    @GetMapping("/getByCode")
    public AjaxResult getResrceByCode(String resrce) {
        Resrce result;
        try {
            result = resrceService.selectByCode(CommonMethods.getSite(), resrce);
        } catch (Exception e) {
            logger.error("getResrceById -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success(result);
    }

    @ResponseBody
    @GetMapping("/list")
    public AjaxResult list(Resrce resrce) {
        List<Resrce> result;
        try {
            resrce.setSite(CommonMethods.getSite());
            result = resrceService.selectEnhanceList(resrce);
        } catch (Exception e) {
            logger.error("list -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success(result);
    }

    @ResponseBody
    @GetMapping("/listByResourceType")
    public AjaxResult listByResourceType(String resourceType) {
        List<Resrce> result;
        try {
            String site = CommonMethods.getSite();
            resourceType = StringUtils.trimHandle(resourceType);
            result = resrceService.listByResourceType(site, resourceType);
        } catch (Exception e) {
            logger.error("listByResourceType -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success(result);
    }

    /**
     * 查询所有数据
     *
     * @return
     */
    @ResponseBody
    @GetMapping("")
    public AjaxResult getResrceList(Resrce resrce){
        List<Resrce> result;
        try {
            EntityWrapper<Resrce> EntityWrapper = new EntityWrapper<>();
            resrce.setSite(CommonMethods.getSite());
            EntityWrapper.setEntity(resrce);
            result = resrceService.selectList(EntityWrapper);
        } catch (Exception e) {
            logger.error("getResrceList -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success(result);
    }

    /**
     * 分页查询数据
     *
     * @param frontPage  分页信息
     * @return
     */
    @ResponseBody
    @GetMapping("/getResrcePageList")
    public AjaxResult getResrcePageList(FrontPage<Resrce> frontPage, Resrce resrce){
        Page result;
        try {
            String site = CommonMethods.getSite();
            resrce.setSite(site);
            EntityWrapper<Resrce> EntityWrapper = new EntityWrapper<>();
            EntityWrapper.setEntity(resrce);
            if (frontPage.getGlobalQuery() != null && !"".equals(frontPage.getGlobalQuery().trim())) {
                //TODO modify global query
                EntityWrapper
                    .like("handle", frontPage.getGlobalQuery())
                    .or().like("changeStamp", frontPage.getGlobalQuery())
                    .or().like("site", frontPage.getGlobalQuery())
                    .or().like("resrce", frontPage.getGlobalQuery())
                    .or().like("description", frontPage.getGlobalQuery())
                    .or().like("statusBo", frontPage.getGlobalQuery())
                    .or().like("processResource", frontPage.getGlobalQuery())
                    .or().like("operationBo", frontPage.getGlobalQuery())
                    .or().like("setupState", frontPage.getGlobalQuery())
                    .or().like("setupDescription", frontPage.getGlobalQuery())
                    .or().like("cncMachine", frontPage.getGlobalQuery())
                    .or().like("pendingStatusBo", frontPage.getGlobalQuery())
                    .or().like("pendingReasonCodeBo", frontPage.getGlobalQuery())
                    .or().like("pendingResourceRcBo", frontPage.getGlobalQuery())
                    .or().like("pendingComments", frontPage.getGlobalQuery())
                    .or().like("erpPlantMaintOrder", frontPage.getGlobalQuery())
                    .or().like("erpEquipmentNumber", frontPage.getGlobalQuery())
                    .or().like("erpInternalId", frontPage.getGlobalQuery())
                    .or().like("erpCapacityCategory", frontPage.getGlobalQuery())
        ;
            }
            result = resrceService.selectPage(frontPage.getPagePlus(), EntityWrapper);
        } catch (Exception e) {
            logger.error("getResrcePageList -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success(result);
    }

    /**
     * 保存和修改公用
     * @param resrce  传递的实体
     * @return  null 失败  实体成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/_save")
    public AjaxResult resrceSave(@RequestBody Resrce resrce) {
        String site = CommonMethods.getSite();
        String user = CommonMethods.getUser();
        int count;
        try {
            count = resrceService.insertOrUpdate(resrce) ? 1 : 0;
        } catch (Exception e) {
            logger.error("resrceSave -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success(count == 0 ? null : resrce);
    }

    /**
     * 根据id删除对象
     * @param id  实体ID
     * @return 0 失败  1 成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.DELETE, value = "/{id:.+}")
    public AjaxResult resrceDelete(@PathVariable("id") String id){
        int count;
        try {
            count = resrceService.deleteById(id) ? 1 : 0;
        } catch (Exception e) {
            logger.error("resrceDelete -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success("count: " + count);
    }

    /**
     * 批量删除对象
     * @param ids 实体集合ID
     * @return  0 失败  1 成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/_batchDelete")
    public AjaxResult removeByIds(List<String> ids){
        int count;
        try {
            count = resrceService.deleteBatchIds(ids) ? 1 : 0;
        } catch (Exception e) {
            logger.error("resrceBatchDelete -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success("count: " + count);
    }
}